<template>
  <div class="fixed-button" v-if="hasSaveButton">
    <el-button
      type="primary"
      @click="saveData"
      :loading="saving"
      :disabled="saving || formReadOnly"
      >保存</el-button
    >
  </div>
  <el-collapse
    v-model="activeNames"
    @change="handleChange"
    :style="{ marginTop: hasSaveButton ? '60px' : '5px' }"
  >
    <el-collapse-item title="设计评价实施报告单内容" name="1">
      <el-form
        :model="reportData"
        label-width="auto"
        label-position="left"
        style="max-width: 600px"
        class="form-content"
      >
        <el-form-item label="项目名">
          <el-input
            v-model="reportData.project_name"
            class="read-only-input"
            readonly
          />
        </el-form-item>
        <el-form-item label="项目号">
          <el-input
            v-model="reportData.project_id"
            class="read-only-input"
            readonly
          />
        </el-form-item>
        <el-form-item label="型号">
          <el-input
            v-model="reportData.model_code"
            class="read-only-input"
            readonly
          />
        </el-form-item>
        <el-form-item label="工厂">
          <el-input
            v-model="reportData.factory"
            class="read-only-input"
            readonly
          />
        </el-form-item>
        <el-form-item label="市场">
          <el-input
            v-model="reportData.send_dest"
            class="read-only-input"
            readonly
          />
        </el-form-item>
        <el-form-item label="产品等级">
          <el-input
            v-model="reportData.project_level"
            class="read-only-input"
            readonly
          />
        </el-form-item>
        <el-form-item label="DR种类">
          <el-input
            :v-model="
              reportData.dr_type === '其他'
                ? reportData.dr_type_other
                : reportData.dr_type
            "
            class="read-only-input"
            readonly
          />
        </el-form-item>
        <el-form-item label="实施日期">
          <el-date-picker
            v-model="reportData.impl_date"
            type="date"
            placeholder="请选择日期"
            style="width: 100%"
            disabled="true"
          />
        </el-form-item>
        <el-form-item label="DR有效性">
          <el-col :span="3" class="text-center">
            <span class="text-gray-500"> 出席率</span>
          </el-col>
          <el-col :span="6">
            <el-input v-model="reportData.attendance" disabled="true">
              <template v-slot:append>%</template>
            </el-input>
          </el-col>
          <el-col :span="2" class="text-center">
            <span class="text-gray-500"></span>
          </el-col>
          <el-col :span="2" class="text-center">
            <span class="text-gray-500"> 会议</span>
          </el-col>
          <el-col :span="7">
            <el-radio-group
              v-model="reportData.is_meeting_valid"
              disabled="true"
            >
              <el-switch
                disabled="true"
                v-model="reportData.is_meeting_valid"
                inline-prompt
                class="ml-2"
                style="
                  --el-switch-on-color: #13ce66;
                  --el-switch-off-color: #ff4949;
                "
                active-text="有效"
                inactive-text="无效"
              />
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="指摘数">
          <el-row>
            <el-col :span="7" class="text-left">
              <span> ×件数: </span>
            </el-col>
            <el-col :span="15">
              <el-input
                :v-model="
                  reportData.blameCounts ? reportData.blameCounts['×'] : 0
                "
                readonly
                class="read-only-input"
              >
              </el-input>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7" class="text-left">
              <span> △件数: </span>
            </el-col>
            <el-col :span="15">
              <el-input
                :v-model="
                  reportData.blameCounts ? reportData.blameCounts['△'] : 0
                "
                readonly
                class="read-only-input"
              >
              </el-input>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7" class="text-left">
              <span> □件数: </span>
            </el-col>
            <el-col :span="15">
              <el-input
                :v-model="
                  reportData.blameCounts ? reportData.blameCounts['□'] : 0
                "
                readonly
                class="read-only-input"
              >
              </el-input>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7" class="text-left">
              <span> 确认件数: </span>
            </el-col>
            <el-col :span="15">
              <el-input
                :v-model="
                  reportData.blameCounts ? reportData.blameCounts['确认'] : 0
                "
                readonly
                class="read-only-input"
              >
              </el-input>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-collapse-item>
    <el-collapse-item title="指摘内容" name="2">
      <BlameView
        ref="blameViewRef"
        :userId="userId"
        :formReadOnly="formReadOnly"
        :formData="blameData"
        @onDataChange="onBlameDataChange"
        lock-scroll
      ></BlameView>
    </el-collapse-item>
  </el-collapse>
</template>
<script lang="ts" setup>
import {
  reactive,
  ref,
  onMounted,
  getCurrentInstance,
  toRefs,
  nextTick,
  watch,
} from "vue";
import { useRouter } from "vue-router";
import BlameView from "./BlameView.vue";
import { ElMessage } from "element-plus";

const instance = getCurrentInstance();
const { $http } = instance?.appContext.config.globalProperties as any;
const router = useRouter();
const hasSaveButton = ref(true);
const saving = ref(false);
const loading = ref(false);
const blameViewRef = ref<any>(null);
const inited = ref(false);
const form_uid = ref();
const userId = ref();
const formReadOnly = ref(false);
const form: { [key: string]: any } = ref({});
const activeNames = ref(["1", "2"]);
const createrEditable = ref(true);
const replierEditable = ref(true);
const reportData: { [key: string]: any } = ref({});
const blameData: { [key: string]: any } = ref({});
const handleChange = (val: string[]) => {
  console.log(val);
};

onMounted(() => {
  form_uid.value = router.currentRoute.value.query.uid as string;
  userId.value = router.currentRoute.value.query.userId as string;
  let checkoutUserId = router.currentRoute.value.query.checkUserId as string;
  let readonlyStr = router.currentRoute.value.query.readonly as string;
  let saveButtonStr = router.currentRoute.value.query.saveButton as string;

  if (checkoutUserId) {
    formReadOnly.value = checkoutUserId !== userId.value;
  } else {
    formReadOnly.value = "false" !== readonlyStr;
  }

  hasSaveButton.value = "false" !== saveButtonStr;

  loadData();
  (window as any).setFormReadOnly = setFormReadOnly;
  (window as any).saveData = saveData;
});

const setFormReadOnly = (isReadOnly: boolean) => {
  formReadOnly.value = isReadOnly;
};

const saveData = async () => {
  let blameFormData = blameViewRef.value.getFormData();
  saving.value = true;
  let errorMsg = null;
  try {
    const saveBlamesUrl = "/saveBlame";
    console.log("保存指摘表单数据：", blameFormData);
    const response2 = await $http.post(saveBlamesUrl, blameFormData);
    console.log("提交结果", response2.data);
    ElMessage({
      type: "success",
      message: "保存成功",
    });
    setDirty(false);
  } catch (error) {
    console.log(error);
    errorMsg = error;
    ElMessage({
      type: "error",
      message: error,
    });
  }
  saving.value = false;
  return errorMsg;
};

const loadData = () => {
  $http
    .get("/getBlameReplyFormByBlameUid?blameUid=" + form_uid.value)
    .then((response: { data: any }) => {
      console.log("评审单查询结果", response.data);
      reportData.value = response.data.report;
      blameData.value = response.data.blames[0];
      blameData.value.form_uid = form_uid.value;
      // form.value = {
      //   ...reportData,
      //   ...blameDatas[0],
      // };
      nextTick(async () => {
        await blameViewRef.value.setFormData(blameData.value, userId.value);
        setDirty(false);
        inited.value = true;
      });
    })
    .catch((error: any) => {
      console.log(error);
      inited.value = true;
    });
};

const onBlameDataChange = (subject: string, formData: any) => {
  console.log("接收到子页数据：", formData);
  //blameForms[subject] = formData;
  setDirty(true);
};

const setDirty = (isDirty: boolean) => {
  console.log("是否修改 ==> " + isDirty);
  let win = window as any;
  if (win.java && win.java.setDirty) {
    win.java.setDirty(isDirty);
  }
};
</script>
<style>
.text-left {
  text-align: left;
  width: 15px;
}
.fixed-button {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 999;
}
.form-content {
  /* 确保表单内容不被保存按钮遮挡 */
  /* margin-top: 70px; */
  margin-top: 10px;
}
.read-only-input .el-input__inner {
  background-color: #f5f5f5;
}
.read-only-input .el-input__wrapper {
  background-color: #f5f5f5;
}
.el-collapse .el-collapse-item__header {
  font-size: 16px;
  font-weight: bold;
}
</style>
